/*
 * Copyright (c) 2021. by xujichang(xujc@yisa com.www.yisa.com) All rights reserved.
 */

package com.gp.billsrecord.extensions

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.InputStream


fun BitmapFactory.decodeUri(context: Context, uri: Uri): Bitmap? {
    val outBoundsOptions = obtainOutBoundsOptions(context, uri)
    val inputStream = context.contentResolver.openInputStream(uri)
    return inputStream?.run {
        doCompress(doScale(inputStream, outBoundsOptions))
    }
}

/**
 * 质量压缩
 */
private fun doCompress(bitmap: Bitmap?): Bitmap? {
    //暂时不做质量压缩
    return bitmap
}

/**
 * 比例压缩
 */
private fun doScale(inputStream: InputStream, options: BitmapFactory.Options): Bitmap? {
    val bitmapOptions = calculateBitmapOptions(options)
    return bitmapOptions?.run {
        BitmapFactory.decodeStream(inputStream, null, this)
    }
}

private fun calculateBitmapOptions(outBoundsOptions: BitmapFactory.Options): BitmapFactory.Options? {
    val originalWidth = outBoundsOptions.outWidth
    val originalHeight = outBoundsOptions.outHeight
    if (originalHeight == -1 || originalWidth == -1) {
        return null
    }
    val standardWidth = 720
    val standardHeight = 1080
    val simpleSize = if (originalWidth > originalHeight && originalWidth > standardWidth) {
        originalWidth.div(standardWidth)
    } else if (originalHeight > originalWidth && originalHeight > standardHeight) {
        originalHeight.div(standardHeight)
    } else {
        1
    }
    return BitmapFactory.Options().apply {
        inSampleSize = simpleSize
        inPreferredConfig = Bitmap.Config.ARGB_8888
    }
}

private fun obtainOutBoundsOptions(context: Context, uri: Uri): BitmapFactory.Options {
    val uriInputStream = context.contentResolver.openInputStream(uri)
    return uriInputStream.use {
        val outBoundsOptions = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
            inPreferredConfig = Bitmap.Config.ARGB_8888
        }
        BitmapFactory.decodeStream(it, null, outBoundsOptions)
        outBoundsOptions
    }
}